import React, { PureComponent } from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { FormInstance } from 'antd/lib/form';
import { Modal, Button, Timeline, message, Input, Table, Form, Row, Col, Select, Space, Radio, InputNumber } from 'antd';
import moment from 'moment';
import PropTypes from 'prop-types';
import styles from './index.less'
import * as echarts from 'echarts';
import { EChartsType } from 'echarts/core';
import { getDicByKey, getDictOptionsByCode } from '@/support/common';


const FormItem = Form.Item;
const { TextArea } = Input;
//  预警展示信息配置
const baseConfig = [
  {
    key: 'vin',
    label: '车辆VIN码',
  },
  {
    key: 'brandName',
    label: '品牌',
  },
  {
    key: 'seriesName',
    label: '车系',
  },
  {
    key: 'typeName',
    label: '车型',
  },
  {
    key: 'batteryType',
    label: '电池类型',
  },
  {
    key: 'batterySupplier',
    label: '电池供应商',
  },
  {
    key: 'batteryCode',
    label: '电池包编号',
  },
  {
    key: 'warningDate',
    label: '预警时间',
  },
  {
    key: 'type',
    label: '预警类型',
  },
  /* {
    key: 'level',
    label: '预警等级',
  }, */
]
const warningConfig = {
  0: '低风险',
  1: '中风险',
  2: '高风险',
}
//  工单列表颜色配置
const colorConfig = {
  0: '#45b97c',
  1: '#FFA500',
  2: '#FF0000',
}
const statusConfig = {
  0: '未处理',
  1: '处理中',
  2: '已处理',
}

//  预警类型对应数据字段  (1:过压; 2:欠压; 3:过温; 4:一致性差; 5:温差过大; 6:SOC跳变)
const typeKeysConfig = {
  1: ['maxVoltage', 'overVoltageCounts'],
  2: ['minVoltage', 'underVoltageCounts'],
  3: ['maxTemperature', 'overTemperatureCounts'],
  4: ['maxVoltageDiff', 'maxVoltage', 'minVoltage', 'overVoltageDiffCounts'],
  5: ['maxTemperatureDiff', 'maxTemperature', 'minTemperature', 'overTemperatureDiffCounts'],
  6: ['socPlunge', 'maxSoc', 'minSoc','overPlungeCounts']
}

//  自定义 tooltip 配置
const tooltipConfig = {
  1: [
    {
      label: '当日最高单体电压',
      key: 'maxVoltage',
    },
    {
      label: '标注值',
      key: 'standard'
    },
    {
      label: '当日过压次数',
      key: 'overVoltageCounts'
    }
  ],
  2: [
    {
      label: '当日最低单体电压',
      key: 'minVoltage',
    },
    {
      label: '标注值',
      key: 'standard',
    },
    {
      label: '当日欠压次数',
      key: 'underVoltageCounts',
    }
  ],
  3: [
    {
      label: '当日最高单体温度',
      key: 'maxTemperature',
    },
    {
      label: '标注值',
      key: 'standard',
    },
    {
      label: '当日过温次数',
      key: 'overTemperatureCounts',
    },
  ],
  4: [
    {
      label: '最高单体电压',
      key: 'maxVoltage',
    },
    {
      label: '最低单体电压',
      key: 'minVoltage',
    },
    {
      label: '压差',
      key: 'maxVoltageDiff',
    },
    {
      label: '压差标注值',
      key: 'standard',
    },
    {
      label: '当日压差过大次数',
      key: 'overVoltageDiffCounts',
    },
  ],
  5: [
    {
      label: '最高单体温度',
      key: 'maxTemperature',
    },
    {
      label: '最低单体温度',
      key: 'minTemperature',
    },
    {
      label: '温差',
      key: 'maxTemperatureDiff',
    },
    {
      label: '温差标注值',
      key: 'standard',
    },
    {
      label: '当日温差过大次数',
      key: 'overTemperatureDiffCounts',
    },
  ],
  6: [
    {
      label: 'SOC最高值',
      key: 'maxSoc',
    },
    {
      label: 'SOC最低值',
      key: 'minSoc',
    },
    {
      label: 'SOC骤降',
      key: 'socPlunge',
    },
    {
      label: '骤降标注值',
      key: 'standard',
    },
    {
      label: '当日骤降过大次数',
      key: 'overPlungeCounts',
    },
  ]
}

const typeChartConfig = {
  1: {
    standard: '4.35',
    unit: 'V',
    title: '当日最高单体电压',
    yName: '电压值（V）',
  },
  2: {
    standard: '2.2',
    unit: 'V',
    title: '当日最低单体电压',
    yName: '电压值（V）',
  },
  3: {
    standard: '53',
    unit: '℃',
    title: '当日最高单体温度',
    yName: '温度值（℃）',
  },
  4: {
    standard: '0.2',
    unit: 'V',
    title: '当日最高压差',
    yName: '电压值（V）',
  },
  5: {
    standard: '12',
    unit: '℃',
    title: '当日最高温差',
    yName: '温度值（℃）',
  },
  6: {
    standard: '8',
    unit: '%',
    title: '当日最高骤降幅度',
    yName: '百分比（%）',
  },
}

const mapStateToProps = (state: any) => ({
  warningDetail: state.warningDetail,
  loading: state.loading.models["warningDetail"],
})
class WarningDetailModal extends PureComponent<any, any> {
  static contextTypes = {
    dicData: PropTypes.any
  };
  constructor(props: any) {
    super(props);
    this.state = {
      warningList: [],  //  预警列表
      currentCode: '',  //  当前预警code
      currentSorceData: {},
      currentData: {},  //  当前预警数据（文本展示）
      lineChartData: {},  //  
      myChart: null as unknown as EChartsType,
      // chart2: null as unknown as EChartsType,
    }
  }

  componentDidMount() {}

  componentDidUpdate(prevProps: any) {
    const { modalVisible } = this.props
    if (modalVisible && modalVisible !== prevProps.modalVisible) {
      const { flag, param } = this.props;
      const params = {
        flag,
        param
      }
      this.setState({
        myChart: echarts.init(document.getElementById('myChart') as HTMLElement),
      }, () => {
        this.getWarningList(params);
      })
    }
  }

  //  预警列表
  getWarningList = (params: any) => {
    const { dispatch } = this.props
    dispatch({
      type: 'warningDetail/getDataWithRes',
      payload: {
        url: '/battery/monitor/warning/list',
        ...params,
      },
      callback: (res: any) => {
        if (res.statusCode === '0' && res.data.warningList) {
          this.setState({
            warningList: res.data.warningList || [],
            currentCode: res.data.warningList[0]?.code,
          }, () => {
            const { currentCode } = this.state;
            if (currentCode) {
              this.getWarningDetail(currentCode);
              this.getChartData(currentCode);
            }
          })
        }
      }
    })
  }

  //  预警详情
  getWarningDetail = (code: any) => {
    const { dispatch } = this.props;
    // const _this = this;
    dispatch({
      type: 'warningDetail/getDataWithRes',
      payload: {
        url: '/battery/monitor/warning/search',
        code,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          this.setState({
            currentSorceData: res.data,
            currentData: {
              ...res.data,
              type: getDicByKey(this.context.dicData, 'faultType', res.data.type + '')
            }
          })
        }
      }
    })
  }

  //  折线图数据
  getChartData = (code: any) => {
    const { dispatch } = this.props
    dispatch({
      type: 'warningDetail/getDataWithRes',
      payload: {
        url: '/battery/monitor/warning/bigdata/indicators',
        code,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          const { myChart } = this.state;
          const lineData = this.formatLineChartData(res.data.list);
          const lineOption = this.formatLineOption(lineData);
          myChart.setOption(lineOption);
          // this.setState({})
        }
      }
    })
  }

  //  整理chart所需数据
  formatLineChartData = (list: any[]) => {
    const daysList = this.createDaysList(30)
    const { currentSorceData: { type } } = this.state;
    const keys = typeKeysConfig[type];
    let temp: any = [];
    let tempItem: any = {};
    const res = {
      type,
      typeName: getDicByKey(this.context.dicData, 'faultType', type + ''),
      daysList: daysList,
      ...typeChartConfig[type],
      data: [],
      dataObj: {},
      
    };
    daysList.forEach(d => {
      let tempData = {}
      let val = 0
      keys.forEach((k: string) => {
        tempData[k] = 0
      })
      list.some((item) => {
        const status = d === item.date
        if (status) {
          val = item[keys[0]] || 0;
          keys.forEach((k: string) => {
            tempData[k] = item[k] || 0;
          })
        }
        return status;
      })
      temp.push(val);
      tempItem[d] = tempData;
    })
    res.data = temp;
    res.dataObj = tempItem;
    return res
  }

  //  自定义 tooltip
  formatTooltip = (x: string, lineData: any) => {
    const { type, standard, unit, dataObj } = lineData
    let itemConfig = tooltipConfig[type]
    let res: any[] = []
    res.push(`<div>${x}</div>`);
    itemConfig.forEach((item: any, idx: number) => {
      let tempSpan = `<div>${item.label}：`;
      if (item.key === 'standard') {
        tempSpan += standard
      } else {
        tempSpan += dataObj[x][item.key]
      }
      if (item.key.indexOf('Counts') === -1) {
        tempSpan += unit
      }
      tempSpan += '</div>'
      res.push(tempSpan)
    })
    return res.join('')
  }


  //  整理 chart option
  formatLineOption = (lineData: any) => {
    const { type, typeName, daysList, standard, unit, title, yName, dataObj, data } = lineData;
    return {
      grid: {
        top: '20%',
        left: '5%',
        right: '5%',
        bottom: '10%',
        containLabel: true
      },
      tooltip: {
        trigger: 'axis',
        borderWidth: 1,
        axisPointer: {
          type: 'shadow'
        },
        backgroundColor: 'rgba(0, 0, 0, .6)',
        textStyle: {
          color: '#fff',
        },
        extraCssText: 'z-index: 2',
        formatter: (params: any) => {
          const str = this.formatTooltip(params[0]['axisValue'], lineData)
          return `<div>${str}</div>`
        }
      },
      legend: [{
        top: '8px',
        // right: '0%',
        orient: 'horizontal',
        data: [title],
        itemWidth: 0,
        itemHeight: 0,
        itemGap: 0,
        // borderRadius: 4,
        icon: 'none',
        textStyle: {
          // color: '#228CFF',
          // fontFamily: 'Alibaba PuHuiTi',
          fontSize: 12,
          fontWeight: 400
        }
      }],
      xAxis: {
        type: 'category',
        data: daysList,
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          show: true,
          textStyle: {
            color: '#393939' //X轴文字颜色
          }
        }
      },
      yAxis: [
        {
          type: 'value',
          name: yName,
          minInterval: 1,
          nameTextStyle: {
            color: '#000',
            // fontFamily: 'Alibaba PuHuiTi',
            fontSize: 12,
            fontWeight: 400,
            padding: [0, 0, 0, -20], // 四个数字分别为上右下左与原位置距离
          },
          nameGap: 8,  // 表现为上下位置
          axisLine: {
            show: true,
            lineStyle: {
              color: '#eeeeee'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#393939',
            fontSize: 14
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: '#eeeeee'
            }
          }
        }
      ],
      series: [{
        name: title,
        type: 'line',
        symbol: 'none',
        symbolSize: 0,
        color: '#F59E2D',
        data: data,
        markLine: {
          // symbol: ['none', 'none'],
          data: [
            {
              name: '标注值',
              yAxis: standard,
              lineStyle: { type: 'dashed', color: '#000', width: 1 },
            },
          ]
        }
      }]
    }
  }


  //  近30天（不包括今天）
  createDaysList = (num: number) => {
    const len = num + 1;
    let ds = [...new Array(len)].map((i, idx) => moment().startOf("day").subtract(idx, "days").format("YYYY-MM-DD"));
    const res = ds.slice(1).reverse()
    return res;
  }

  handleSelectWarning = (code: any) => {
    const { currentCode } = this.state
    if (currentCode == code) return;
    this.setState({
      currentCode: code,
    }, () => {
      this.getWarningDetail(code)
      this.getChartData(code)
    })
  }

  close = () => {
    const { closeModal } = this.props;
    closeModal();
  }

  render() {
    const { modalVisible } = this.props;
    const { warningList, currentCode, currentData } = this.state

    const footer = (
      <div>
        <Button type="primary" onClick={this.close}>
          关闭
        </Button>
      </div>
    )

    return (
      <Modal
        title="预警详情"
        footer={footer}
        visible={modalVisible}
        // width={1050}
        width={1250}
        onCancel={this.close}
      >
        <div className={styles.warningDetailWrapper}>
          <Row justify="space-between">
            <Col span={8}
              style={{
                height: '100%',
                paddingTop: '6px',
                overflowX: 'hidden',
                overflowY: 'auto'
              }}
            >
              <Timeline mode="left">
                {
                  warningList.map((item: any, i: number) => (
                    <Timeline.Item
                      key={i}
                      color={colorConfig[item.level]}
                      label={<div>
                        <div>{item.warningDate}</div>
                        <div>预警编号:{item.code}</div>
                      </div>}
                      onClick={() => {
                        this.handleSelectWarning(item.code)
                      }}
                    >
                      <div>
                        <div>
                          <span
                            style={{
                              display: 'inline-block',
                              padding: '2px 12px',
                              marginRight: '4px',
                              backgroundColor: item.code === currentCode ? colorConfig[item.level] : ''
                            }}
                          >{warningConfig[item.level]}</span>
                          <span style={{
                            display: 'inline-block',
                            padding: '2px 12px',
                            color: '#fff',
                            backgroundColor: item.statusConfig == 1 ? 'rgb(51,51,51)' : 'rgb(170,170,170)',
                          }}>{statusConfig[item.status]}</span>
                        </div>
                        {item.status == 0 ? null : (
                          <div>
                          工单编号:{item.orderCode}
                        </div>
                        )}
                      </div>
                    </Timeline.Item>
                  ))
                }
              </Timeline>
            </Col>
            <Col span={15}>
              <div className={styles.infoBox}>
                {
                  baseConfig.map((item, i) => (
                    <div key={item.key} className={styles.infoItem}>
                      <div className={styles.itemFl}>{item.label}</div>
                      <div className={styles.itemFr}>{currentData[item.key]}</div>
                    </div>
                  ))
                }
              </div>
              <div className={styles.chartsCell}>
                <div id={'myChart'} className={styles.myChart}>

                </div>
                {/* <div id={'chart2'} className={styles.chart2}>

                </div> */}
              </div>
            </Col>
          </Row>
        </div>
        
      </Modal>
    )
  }
}
export default connect(mapStateToProps)(WarningDetailModal);
